package com.mingtu.dzpatrol.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.dzpatrol.R;
import com.mingtu.dzpatrol.activity.InfoActivity;
import com.mingtu.dzpatrol.activity.ResetPasswordActivity;
import com.mingtu.dzpatrol.base.BaseFragment;
import com.mingtu.dzpatrol.bean.UpdateBean;
import com.mingtu.dzpatrol.callback.StringDialogCallback;
import com.mingtu.dzpatrol.utils.Constant;
import com.mingtu.dzpatrol.utils.HProgressDialogUtils;
import com.mingtu.dzpatrol.utils.IntentUtils;
import com.mingtu.dzpatrol.utils.SPTools;
import com.mingtu.dzpatrol.utils.StatusBarUtil;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate._XUpdate;
import com.xuexiang.xupdate.service.OnFileDownloadListener;
import com.xuexiang.xutil.app.PathUtils;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Tab3Fragment extends BaseFragment {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.layout_reset_password)
    RelativeLayout layoutResetPassword;
    @BindView(R.id.tv_version_text)
    TextView tvVersionText;
    @BindView(R.id.tip_view)
    View tipView;
    @BindView(R.id.tv_version_name)
    TextView tvVersionName;
    @BindView(R.id.layout_version)
    RelativeLayout layoutVersion;
    @BindView(R.id.layout_top)
    LinearLayout layoutTop;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    private String name;
    private String downloadUrl;
    private boolean versionFlag = false;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab3;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView(View view) {
        StatusBarUtil.addStatusBarHeight(statusBarView);
    }

    @Override
    protected void getData() {
        name = SPStaticUtils.getString(SPTools.userName);
        if (!StringUtils.isEmpty(name)) {
            tvName.setText(name);
        }

        getVersionInfo();
    }

    @OnClick({R.id.layout_top, R.id.layout_reset_password, R.id.layout_version})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_top:
                //用户信息
                String mobile = SPStaticUtils.getString(SPTools.mobile);//联系方式
                String roleName = SPStaticUtils.getString(SPTools.roleName);
                String deptName = SPStaticUtils.getString(SPTools.deptName);

                Bundle bundle = new Bundle();
                bundle.putString("name", name);
                bundle.putString("mobile", mobile);
                bundle.putString("roleName", roleName);
                bundle.putString("deptName", deptName);
                IntentUtils.getInstance().readyGo(getActivity(), InfoActivity.class, bundle);
                break;
            case R.id.layout_reset_password:
                IntentUtils.getInstance().readyGo(getActivity(), ResetPasswordActivity.class);
                break;
            case R.id.layout_version:
                if (versionFlag) {
                    //下载安装APK
                    XXPermissions.with(this)
                            // 不适配 Android 11 可以这样写
                            .permission(Permission.Group.STORAGE)
                            // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
//                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE) || permissions.contains(Permission.READ_EXTERNAL_STORAGE)) {
                                        installAPK();
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (never) {
                                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                        new XPopup.Builder(ActivityUtils.getTopActivity())
                                                .isDestroyOnDismiss(true)
                                                .dismissOnTouchOutside(true)
                                                .hasShadowBg(true)
                                                .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_storage_auth),
                                                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                                        new OnConfirmListener() {
                                                            @Override
                                                            public void onConfirm() {
                                                                XXPermissions.startPermissionActivity(ActivityUtils.getTopActivity(), permissions);
                                                            }
                                                        }, null, false)
                                                .show();
                                    }
                                }
                            });

                } else {
                    ToastUtils.showLong("已经是最新版本");
                }
                break;

        }
    }

    private void installAPK() {
        if (StringUtils.isEmpty(downloadUrl)) {
            ToastUtils.showLong("下载文件获取有误！");
            return;
        }
        XUpdate.newBuild(ActivityUtils.getTopActivity())
                .apkCacheDir(PathUtils.getExtDownloadsPath()) //设置下载缓存的根目录
                .build()
                .download(downloadUrl, new OnFileDownloadListener() {   //设置下载的地址和下载的监听
                    @Override
                    public void onStart() {
                        HProgressDialogUtils.showHorizontalProgressDialog(ActivityUtils.getTopActivity(), "下载进度", false);
                    }

                    @Override
                    public void onProgress(float progress, long total) {
                        HProgressDialogUtils.setProgress(Math.round(progress * 100));
                    }

                    @Override
                    public boolean onCompleted(File file) {
                        HProgressDialogUtils.cancel();
                        tipView.setVisibility(View.GONE);
                        versionFlag = false;
                        LogUtils.e("apk", "apk下载完毕，文件路径：" + file.getPath());
                        _XUpdate.startInstallApk(ActivityUtils.getTopActivity(), file); //填写文件所在的路径

                        return false;
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        HProgressDialogUtils.cancel();
//                                    tipView.setVisibility(View.VISIBLE);
//                                    versionFlag = true;
                    }
                });
    }


    /**
     * 获取版本信息
     */
    private void getVersionInfo() {
        OkGo.<String>get(Constant.getInstance().GET_UPDATE)
                .tag(this)
                .execute(new StringDialogCallback(ActivityUtils.getTopActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            UpdateBean updateBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                updateBean = new UpdateBean();
                                updateBean = gson.fromJson(result, UpdateBean.class);
                                downloadUrl = updateBean.getDownloadUrl();
                                int currentVersion = AppUtils.getAppVersionCode();
                                String versionCode = updateBean.getVersionCode();
                                if (!StringUtils.isEmpty(versionCode)) {
                                    if (currentVersion < Integer.parseInt(versionCode)) { //当前版本小于远程版本提示更新
                                        tipView.setVisibility(View.VISIBLE);
                                        versionFlag = true;
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        LogUtils.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

}